package cqrtplm.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationService;
import com.hustcad.plm.pdm.lifestage.model.dto.EntityLifeCycleDTO;
import com.hustcad.plm.pdm.modeling.model.dto.TyplmGeneralOperationDTO;
import com.hustcad.plm.pdm.mpm.service.TyplmTechnologyWorkFlowService;
import com.hustcad.plm.pdm.user.service.TyplmOrgService;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.org.UserDO;
import cqrtplm.entity.DeptRoleDO;
import cqrtplm.mapper.DeptRoleMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


public class CommonUtil {

    // 零部件类型转换
    public static String convertPartType(String type) throws Exception {
        if ("图样代号".equals(type)) {
            type = "PatternCode";
        } else if ("物料码".equals(type)) {
            type = "MaterialCode";
        } else if ("标准件".equals(type)) {
            type = "Standard";
        }
        return type;
    }

    //段号字段处理
    public static String concatSegmNum(String segmNum) throws Exception {
        if (StringUtils.isNotBlank(segmNum)) {
            if (segmNum.contains("（"))
                segmNum = segmNum.replace("（", "(");
            if (segmNum.contains("(")) {
                segmNum = segmNum.substring(0, segmNum.indexOf("("));
            }
        }
        return segmNum;
    }

    public static void setProcessObjectLife(String key, String lifeCycleCode, List<EntityLifeCycleDTO> entityLifeCycleList) {
        if (key.equals("Y")) {
            TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();
            List<JSONObject> currentObj = new ArrayList();
            for (EntityLifeCycleDTO entityLifeCycleDTO : entityLifeCycleList) {
                String otype = entityLifeCycleDTO.getOtype();
                BigInteger oid = entityLifeCycleDTO.getOid();
                if ("ty.inteplm.mpm.CTyMPMProcessPlan".equalsIgnoreCase(entityLifeCycleDTO.getOtype()) || "ty.inteplm.mpm.CTyMPMOperation".equalsIgnoreCase(entityLifeCycleDTO.getOtype())) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("otype", otype);
                    jsonObject.put("oid", oid);
                    currentObj.add(jsonObject);
                }
            }

            goDTO.setCurrentObj(currentObj);
            List<JSONObject> list = new ArrayList();
            if (CollUtil.isNotEmpty(currentObj)) {
                TyplmTechnologyWorkFlowService typlmTechnologyWorkFlowService = (TyplmTechnologyWorkFlowService) SpringUtil.getBean(TyplmTechnologyWorkFlowService.class);
                typlmTechnologyWorkFlowService.getAllObjWorkFlow(goDTO, list);
            }

            if (CollUtil.isNotEmpty(list)) {
                List<String> keyList = (List) entityLifeCycleList.stream().map((obj) -> obj.getOtype() + ":" + obj.getOid()).distinct().collect(Collectors.toList());

                for (JSONObject object : list) {
                    String otype = parseObjOtype(object.getString("otype"));
                    BigInteger oid = TyplmEntityBaseUtil.getOidByStr(object.getString("oid"), BigInteger.ZERO);
                    String jsonkey = otype + ":" + oid;
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(otype) && !TyplmEntityBaseUtil.isEmptyOid(oid) && !keyList.contains(jsonkey)) {
                        EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                        entityLifeCycleDTO.setOid(object.getBigInteger("oid"));
                        entityLifeCycleDTO.setOtype(parseObjOtype(object.getString("otype")));
                        entityLifeCycleDTO.setLifeCycleStageKey(lifeCycleCode);
                        entityLifeCycleList.add(entityLifeCycleDTO);
                        keyList.add(jsonkey);
                    }
                }
            }
        }
    }

    public static void setSTExecutionVariable(ChgFormVO chgFormVO, String conditionBranch, DelegateExecution execution) {
        String formData = chgFormVO.getFormData();
        BigInteger createrId = chgFormVO.getCreatorOid();
        TyplmEnumerationService typlmEnumerationService = SpringUtil.getBean(TyplmEnumerationService.class);
        Map<String, String> enmumap = typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("factory")).get("factory");
        List<String> createDepartMent = new ArrayList<>();
        createDepartMent = getUserDepartMent(createDepartMent, createrId, TableTypeConstrant.TY_USER_OTYPE);
        JSONObject testObj = JSONObject.parseObject(formData);
//        JSONObject testObj = formDataJson.getJSONObject("testObj");
        String ZYDJ = testObj.getString("ZYDJ");//重要等级
        String SFGGZTDD = testObj.getString("SFGGZTDD");//是否更改在途订单
        String ZJCD = testObj.getString("ZJCD");//整机产地
        ZJCD = covertFactory(ZJCD, enmumap);
        String LJHYD = testObj.getString("LJHYD");//零件货源地
        LJHYD = covertFactory(LJHYD, enmumap);
        String KHPD = testObj.getString("KHPD");//客户判定
        String SFGGGYWJ = testObj.getString("SFGGGYWJ");//是否更改工艺文件
        JSONArray conditionArray = JSONArray.parseArray(conditionBranch);
        for (int i = 0; i < conditionArray.size(); i++) {
            JSONObject jsonObject = conditionArray.getJSONObject(i);
            String node = jsonObject.getString("node");
            String branchName = jsonObject.getString("branchName");
            String condition = jsonObject.getString("condition");
            if ("审核".equals(node)) {
                boolean ZYDJflag = false;
                boolean ZYDJflag2 = false;
                boolean SFGGZTDDflag = false;
                String[] conditionArr1 = condition.split("\\|\\|");
                for (int j = 0; j < conditionArr1.length; j++) {
                    String condition2 = conditionArr1[j];
                    if (condition2.contains("(")) {
                        String condition3 = condition2.substring(1, condition2.length() - 1);
                        if (condition3.contains("&&")) {
                            String[] conditionArr2 = condition3.split("&&");
                            for (int k = 0; k < conditionArr2.length; k++) {
                                String condition4 = conditionArr2[k];
                                if (condition4.contains("ZYDJ")) {
                                    String ZYDJ1 = condition4.split("=")[1];
                                    if (ZYDJ1.equals(ZYDJ)) {
                                        ZYDJflag = true;
                                    }
                                } else if (condition4.contains("SFGGZTDD")) {
                                    String SFGGZTDD1 = condition4.split("=")[1];
                                    if (SFGGZTDD1.equals(SFGGZTDD)) {
                                        SFGGZTDDflag = true;
                                    }
                                }
                            }
                        }
                    } else {
                        if (condition2.contains("ZYDJ")) {
                            if (condition2.contains("!=")) {
                                String ZYDJ1 = condition2.split("!=")[1];
                                if (!ZYDJ1.equals(ZYDJ)) {
                                    ZYDJflag2 = true;
                                }
                            }
                        }
                    }
                }
                if ((ZYDJflag && SFGGZTDDflag) || ZYDJflag2) {
                    execution.setVariable(branchName, true);
                }
            } else if ("会签".equals(node)) {
                List<Boolean> listflag = new ArrayList<>();
                if (condition.contains("&&")) {
                    String[] conditionArr1 = condition.split("&&");
                    for (int j = 0; j < conditionArr1.length; j++) {
                        String condition2 = conditionArr1[j];
                        if (condition2.contains("ZYDJ")) {
                            String ZYDJ1 = condition2.split("!=")[1];
                            if (!ZYDJ1.equals(ZYDJ)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                        if (condition2.contains("department")) {
                            String department1 = condition2.split("=")[1];
                            if (createDepartMent.contains(department1)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                        if (condition2.contains("KHPD")) {
                            Map<String, String> customerenmumap = typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("BigCustomer")).get("BigCustomer");
                            JSONArray subform47946 = testObj.getJSONArray("subform47946");
                            boolean bigCustomer = false;
                            if (CollectionUtils.isNotEmpty(subform47946)) {
                                for (int k = 0; k < subform47946.size(); k++) {
                                    String customer = subform47946.getJSONObject(k).get("input44037").toString();
                                    if (org.apache.commons.lang.StringUtils.isNotBlank(customer)) {
                                        String[] customerList = customer.split(",");
                                        if (Arrays.asList(customerList).stream().anyMatch(c -> customerenmumap.containsKey(c))) {
                                            bigCustomer = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (bigCustomer) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                        if (condition2.contains("ZJCD")) {
                            String ZJCD1 = condition2.split("=")[1];
                            if (ZJCD.contains(ZJCD1)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                        if (condition2.contains("LJHYD")) {
                            String LJHYD1 = condition2.split("=")[1];
                            if (LJHYD.contains(LJHYD1)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                    }
                } else {
                    if (condition.contains("ZYDJ")) {
                        String ZYDJ1 = condition.split("!=")[1];
                        if (!ZYDJ1.equals(ZYDJ)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                    if (condition.contains("department")) {
                        String department1 = condition.split("=")[1];
                        if (createDepartMent.contains(department1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                    if (condition.contains("KHPD")) {
                        Map<String, String> customerenmumap = typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("BigCustomer")).get("BigCustomer");
                        JSONArray subform47946 = testObj.getJSONArray("subform47946");
                        boolean bigCustomer = false;
                        if (CollectionUtils.isNotEmpty(subform47946)) {
                            for (int j = 0; j < subform47946.size(); j++) {
                                String customer = subform47946.getJSONObject(j).get("input44037").toString();
                                if (org.apache.commons.lang.StringUtils.isNotBlank(customer)) {
                                    String[] customerList = customer.split(",");
                                    if (Arrays.asList(customerList).stream().anyMatch(c -> customerenmumap.containsKey(c))) {
                                        bigCustomer = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (bigCustomer) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                    if (condition.contains("ZJCD")) {
                        String ZJCD1 = condition.split("=")[1];
                        if (ZJCD.contains(ZJCD1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                    if (condition.contains("LJHYD")) {
                        String LJHYD1 = condition.split("=")[1];
                        if (LJHYD.contains(LJHYD1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                }
                boolean flag = true;
                for (int j = 0; j < listflag.size(); j++) {
                    if (!listflag.get(j)) {
                        flag = false;
                        break;
                    }
                }
                execution.setVariable(branchName, flag);
            } else if ("审批".equals(node)) {
                boolean flag = false;
                if (condition.contains("!=")) {
                    String department1 = condition.split("!=")[1];
                    String[] deppartmentArr = department1.split("&&");
                    String department2 = deppartmentArr[0];
                    String department3 = deppartmentArr[1];
                    if (!createDepartMent.contains(department2) && !createDepartMent.contains(department3)) {
                        flag = true;
                    }
                } else {
                    String department1 = condition.split("=")[1];
                    if (createDepartMent.contains(department1)) {
                        flag = true;
                    }
                }
                execution.setVariable(branchName, flag);
            } else if ("知会".equals(node)) {
                List<Boolean> listflag = new ArrayList<>();
                if (condition.contains("&&")) {
                    String[] conditionArr1 = condition.split("&&");
                    for (int j = 0; j < conditionArr1.length; j++) {
                        String condition2 = conditionArr1[j];
                        if (condition2.contains("ZYDJ")) {
                            if (condition2.contains("!=")) {
                                String ZYDJ1 = condition2.split("!=")[1];
                                if (!ZYDJ1.equals(ZYDJ)) {
                                    listflag.add(true);
                                } else {
                                    listflag.add(false);
                                }
                            } else {
                                String ZYDJ1 = condition2.split("=")[1];
                                if (ZYDJ1.equals(ZYDJ)) {
                                    listflag.add(true);
                                } else {
                                    listflag.add(false);
                                }
                            }
                        }
                        if (condition2.contains("ZJCD")) {
                            String ZJCD1 = condition2.split("=")[1];
                            if (ZJCD.contains(ZJCD1)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                        if (condition2.contains("SFGGGYWJ")) {
                            String SFGGGYWJ1 = condition2.split("=")[1];
                            if (SFGGGYWJ1.equals(SFGGGYWJ)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                    }
                } else {
                    if (condition.contains("ZYDJ")) {
                        if (condition.contains("!=")) {
                            String ZYDJ1 = condition.split("!=")[1];
                            if (!ZYDJ1.equals(ZYDJ)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        } else {
                            String ZYDJ1 = condition.split("=")[1];
                            if (ZYDJ1.equals(ZYDJ)) {
                                listflag.add(true);
                            } else {
                                listflag.add(false);
                            }
                        }
                    }
                    if (condition.contains("ZJCD")) {
                        String ZJCD1 = condition.split("=")[1];
                        if (ZJCD.contains(ZJCD1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                    if (condition.contains("SFGGGYWJ")) {
                        String SFGGGYWJ1 = condition.split("=")[1];
                        if (SFGGGYWJ1.equals(SFGGGYWJ)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                }
                boolean flag = true;
                for (int j = 0; j < listflag.size(); j++) {
                    if (!listflag.get(j)) {
                        flag = false;
                        break;
                    }
                }
                execution.setVariable(branchName, flag);
            }
        }
    }

    public static void setJGExecutionVariable(ChgFormVO chgFormVO, String conditionBranch, DelegateExecution execution) {
        String formData = chgFormVO.getFormData();
        JSONObject formDataJson = JSONObject.parseObject(formData);
        JSONObject testObj = formDataJson.getJSONObject("testObj");
        String GGFW = testObj.getString("GGFW");//更改范围
        String reason = testObj.getString("YYFL");
        String ZJCD = testObj.getString("ZJCD");//整机产地
        TyplmEnumerationService typlmEnumerationService = SpringUtil.getBean(TyplmEnumerationService.class);
        Map<String, String> enmumap = typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("factory")).get("factory");
        ZJCD = covertFactory(ZJCD, enmumap);
        String CPLB = testObj.getString("CPLB");//产品类别
        JSONArray conditionArray = JSONArray.parseArray(conditionBranch);
        for (int i = 0; i < conditionArray.size(); i++) {
            JSONObject jsonObject = conditionArray.getJSONObject(i);
            String node = jsonObject.getString("node");
            String branchName = jsonObject.getString("branchName");
            String condition = jsonObject.getString("condition");
            if ("知会".equals(node)) {
                List<Boolean> listflag = new ArrayList<>();
                if (condition.contains("ZYDJ")) {
                    if (condition.contains("!=")) {
                        String ZYDJ1 = condition.split("!=")[1];
                        if (!ZJCD.contains(ZYDJ1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    } else if (condition.contains("=")) {
                        String ZYDJ1 = condition.split("=")[1];
                        if (ZJCD.contains(ZYDJ1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                } else if (condition.contains("ZJCD")) {
                    if (condition.contains("=")) {
                        String ZJCD1 = condition.split("=")[1];
                        if (ZJCD.contains(ZJCD1)) {
                            listflag.add(true);
                        } else {
                            listflag.add(false);
                        }
                    }
                }
                boolean flag = true;
                for (int j = 0; j < listflag.size(); j++) {
                    if (!listflag.get(j)) {
                        flag = false;
                        break;
                    }
                }
                execution.setVariable(branchName, flag);
            } else if ("审核".equals(node)) {
                if (condition.contains("大客户")){
                    Map<String, String> customerenmumap = typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("BigCustomer")).get("BigCustomer");
                    JSONArray subform57714 = formDataJson.getJSONArray("subform57714");
                    boolean bigCustomer = false;
                    if (CollectionUtils.isNotEmpty(subform57714)) {
                        for (int j = 0; j < subform57714.size(); j++) {
                            String customer = subform57714.getJSONObject(j).get("input44037").toString();
                            if (org.apache.commons.lang.StringUtils.isNotBlank(customer)) {
                                String[] customerList = customer.split(",");
                                if (Arrays.asList(customerList).stream().anyMatch(c -> customerenmumap.containsKey(c))) {
                                    bigCustomer = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (bigCustomer) {
                        if ("状态整合".equals(reason) || "设计更改".equals(reason) || "交付提出".equals(reason)) {
                            execution.setVariable(branchName, true);
                        }
                    }
                }
                if (condition.contains("GGFW")) {
                    boolean ggfwFlag=false;
                    if (condition.equals("!=")){
                        if (condition.contains("!=")) {
                            String GGFW1 = condition.split("!=")[1];
                            if (!GGFW.equals(GGFW1)) {
                                ggfwFlag=true;
                            }
                        }
                    } else if (condition.contains("=")) {
                        String GGFW1 = condition.split("=")[1];
                        if (GGFW.contains(GGFW1)) {
                            ggfwFlag=true;
                        }
                    }
                    execution.setVariable(branchName, ggfwFlag);
                }
            }else if ("发起者".equals(node)) {
                if (condition.contains("GGFW")) {
                    if (condition.contains("=")) {
                        String GGFW1 = condition.split("=")[1];
                        if (GGFW.contains(GGFW1)) {
                            execution.setVariable(branchName, true);
                        }else{
                            execution.setVariable(branchName, false);
                        }
                    }
                }
            }
        }
    }

    public static List<String> getUserDepartMent(List<String> deptList, BigInteger oid, String otype) {
        TyplmPrincipalService typlmPrincipalService = SpringUtil.getBean(TyplmPrincipalService.class);
        TyplmOrgService typlmOrgService = SpringUtil.getBean(TyplmOrgService.class);
        PrincipalEntity principalEntity = new PrincipalEntity(oid, otype);
        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(principalEntity);
        typlmOrgService.dealOrgParentPath(outParent);
        if (CollUtil.isNotEmpty(outParent)) {
            for (PrincipalEntity entity : outParent) {
                if (entity instanceof OrgDO) {
                    OrgDO orgDO = (OrgDO) entity;
                    String name = orgDO.getName();
                    if ("重庆润通".equals(name))
                        return deptList;
                    deptList.add(name);
                    getUserDepartMent(deptList, orgDO.getOid(), orgDO.getOtype());
                }
            }
        }
        return deptList;
    }

    private static String parseObjOtype(String type) {
        String result = "";
        if (org.apache.commons.lang3.StringUtils.isEmpty(type)) {
            return result;
        } else {
            String[] otype = type.split("\\|");
            result = otype[0];
            return result;
        }
    }

    public static UserDO getCurrentUserLeader(BigInteger userId, String roleName) {
        PrincipalEntity principalEntity = new PrincipalEntity(userId, TableTypeConstrant.TY_USER_OTYPE);
        TyplmPrincipalService typlmPrincipalService = SpringUtil.getBean(TyplmPrincipalService.class);
        TyplmOrgService typlmOrgService = SpringUtil.getBean(TyplmOrgService.class);
        DeptRoleMapper deptRoleMapper = SpringUtil.getBean(DeptRoleMapper.class);
        TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);
        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(principalEntity);
        typlmOrgService.dealOrgParentPath(outParent);
        if (CollUtil.isEmpty(outParent)) {
            return null;
        }
        BigInteger deptId = null;
        for (PrincipalEntity entity : outParent) {
            if (entity instanceof OrgDO) {
                OrgDO orgDO = (OrgDO) entity;
                String containerotype = orgDO.getContainerotype();
                if (TableTypeConstrant.TY_ORGCONTAINER_OTYPE.equals(containerotype)) {
                    deptId = orgDO.getOid();
                    break;
                }
            }
        }
        if (deptId == null) {
            return null;
        }
        List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectLeaderByDeptIdAndRoleName(String.valueOf(deptId), roleName);
        if (CollUtil.isEmpty(deptRoleDOS)) {
//            throw RTErrorCodeEnum.CUSTOM_EXCEPTION.getException("当前用户所在部门"+roleName+"为空");
            return null;
        }
        UserDO userDO = typlmUserService.queryUserByName(deptRoleDOS.get(0).getUserNo());
        return userDO;
    }

    /**
     * 日期格式转换为字符串
     *
     * @param date
     */
    public static String dateTranlateString(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = dateFormat.format(date);
        return formattedDate;
    }

    /**
     * 字符串转换为日期格式
     *
     * @param dateStr
     */
    public static Date stringTranlateDate(String dateStr) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String covertFactory(String factory, Map<String, String> factoryEnmu) {
        List<String> factorys = new ArrayList<>();
        if (StringUtils.isNotBlank(factory)) {
            String[] factoryList = factory.split(",");
            for (int i = 0; i < factoryList.length; i++) {
                if (factoryEnmu.containsKey(factoryList[i])) {
                    if (!factorys.contains(factoryEnmu.get(factoryList[i])))
                        factorys.add(factoryEnmu.get(factoryList[i]));
                }
            }
        }
        return String.join(",", factorys);
    }

}